package com.dk.shiro;




import com.dk.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


//@Component
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法");
        //创建权限信息对象
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        //添加当前用户的权限字符串（数据库查询）
        List<String> perms =new ArrayList<>();
        perms.add("add");
        perms.add("update");
        perms.add("delexcel");
//
//        info.addRole();
        info.addStringPermissions(perms);
        return info;
    }

    //用来认证的方法（登录）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法...");
        //模拟数据库用户，密码
//        String userName = "admin";
//        String password = "4080765f9ebc5f5b03b3a046723b935f"; //032185 数据库需要保存
//        String salt = "032185";
        User user = new User(123L,"admin","4080765f9ebc5f5b03b3a046723b935f","管理员","032185");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
//        TPerson person = personServiceI.findPersonByName(username);

        if (!username.equals(user.getUsername())) {
            //如果不一致，说明用户不存在
            return null;
        }
        //判断密码 中间参数是密码，是我们数据库查询出来的密码
        // 1、登录用户对象 2、数据库密文密码 3、当前登录用户的盐 4、登录用户的真实名称（用户名）
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),user.getRealname());
    }
}
